const { authApi } = require('../../services/api')
const Toast = require('../../utils/toast')

Page({
  data: {
    loading: false,
    showPhoneLogin: false,
    phone: '',
    password: ''
  },

  onLoad() {
    this.checkLogin()
  },

  // 检查登录状态
  checkLogin() {
    const token = wx.getStorageSync('token')
    if (token) {
      wx.switchTab({ url: '/pages/index/index' })
    }
  },

  // 微信获取手机号登录
  onGetPhoneNumber(e) {
    console.log('获取手机号事件:', e.detail)

    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      // 使用正确的Toast方法
      if (e.detail.errMsg.includes('deny')) {
        Toast('需要授权手机号才能登录')
      } else if (e.detail.errMsg.includes('no permission')) {
        Toast('小程序未获得获取手机号权限，将切换到手机号登录')
        // 显示手机号登录选项
        setTimeout(() => {
          this.showPhoneLogin()
        }, 1500)
      } else {
        Toast('获取手机号失败')
      }
      return
    }

    this.setData({ loading: true })
    Toast.loading('登录中...')

    // 获取微信code
    wx.login({
      success: (res) => {
        if (!res.code) {
          this.setData({ loading: false })
          Toast.hide()
          Toast('获取登录凭证失败')
          return
        }

        // 调用后端接口
        authApi.wechatLogin({
          code: res.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }).then(response => {
          if (response.code === 200) {
            this.loginSuccess(response.data)
          } else {
            throw new Error(response.message || '登录失败')
          }
        }).catch(error => {
          console.error('登录错误:', error)
          Toast(error.message)
        }).finally(() => {
          this.setData({ loading: false })
          Toast.hide()
        })
      },
      fail: () => {
        this.setData({ loading: false })
        Toast.hide()
        Toast('微信登录失败')
      }
    })
  },

  // 手机号登录
  onPhoneLogin() {
    const { phone, password } = this.data

    if (!phone || !password) {
      Toast('请输入手机号和密码')
      return
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Toast('手机号格式不正确')
      return
    }

    this.setData({ loading: true })
    Toast.loading('登录中...')

    authApi.phoneLogin({
      phone,
      password
    }).then(response => {
      if (response.code === 200) {
        this.loginSuccess(response.data)
      } else {
        throw new Error(response.message || '登录失败')
      }
    }).catch(error => {
      Toast(error.message)
    }).finally(() => {
      this.setData({ loading: false })
      Toast.hide()
    })
  },

  // 登录成功处理
  loginSuccess(data) {
    wx.setStorageSync('token', data.token)
    wx.setStorageSync('user', data.user)
    Toast.success('登录成功')
    setTimeout(() => {
      wx.switchTab({ url: '/pages/index/index' })
    }, 1500)
  },

  // 显示/隐藏手机号登录弹窗
  showPhoneLogin() {
    this.setData({ showPhoneLogin: true })
  },

  hidePhoneLogin() {
    this.setData({ showPhoneLogin: false })
  },

  // 表单输入处理
  onPhoneChange(e) {
    this.setData({ phone: e.detail })
  },

  onPasswordChange(e) {
    this.setData({ password: e.detail })
  },

  // 协议查看
  showAgreement() {
    wx.navigateTo({ url: '/pages/webview?url=协议地址' })
  },

  showPrivacy() {
    wx.navigateTo({ url: '/pages/webview?url=隐私地址' })
  }
})